import sys
import os
import json
import requests
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                            QPushButton, QTextEdit, QLineEdit, QLabel, QSystemTrayIcon, 
                            QMenu, QAction, QDialog, QTabWidget, QFormLayout, QCheckBox, 
                            QMessageBox, QSplitter, QFrame, QScrollArea, QStyle)  # 添加QStyle
from PyQt5.QtGui import (QPixmap, QIcon, QFont, QTextCursor, QColor, QPalette, 
                        QTextCharFormat, QBrush, QFontDatabase, QPainter)
from PyQt5.QtCore import Qt, QUrl, QSize, QTimer, QPoint, QThread, pyqtSignal, QSettings

class DeepSeekAPI:
    """DeepSeek API交互类"""
    def __init__(self, api_key=""):
        self.api_key = api_key
        self.api_url = "https://api.deepseek.com/v1/chat/completions"  # 示例URL，需替换为实际地址
    
    def set_api_key(self, api_key):
        self.api_key = api_key
    
    def generate_response(self, messages, callback=None):
        if not self.api_key:
            return "请先设置API密钥"
        try:
            headers = {"Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}"}
            data = {"model": "deepseek-chat", "messages": messages, "temperature": 0.7}
            response = requests.post(self.api_url, headers=headers, json=data)
            response.raise_for_status()
            return response.json()["choices"][0]["message"]["content"]
        except Exception as e:
            return f"API错误: {str(e)}"

class SettingsDialog(QDialog):
    """设置对话框"""
    def __init__(self, parent=None, api_key="", dark_mode=False):
        super().__init__(parent)
        self.setWindowTitle("设置")
        self.setMinimumWidth(400)
        self.api_key = api_key
        self.dark_mode = dark_mode
        
        layout = QVBoxLayout(self)
        
        # 创建标签页
        tabs = QTabWidget()
        
        # API设置标签页
        api_tab = QWidget()
        api_layout = QFormLayout(api_tab)
        
        self.api_key_edit = QLineEdit(api_key)
        api_layout.addRow("API密钥:", self.api_key_edit)
        
        # 主题设置标签页
        theme_tab = QWidget()
        theme_layout = QFormLayout(theme_tab)
        
        self.dark_mode_checkbox = QCheckBox("深色模式")
        self.dark_mode_checkbox.setChecked(dark_mode)
        theme_layout.addRow("主题:", self.dark_mode_checkbox)
        
        # 添加标签页
        tabs.addTab(api_tab, "API设置")
        tabs.addTab(theme_tab, "主题设置")
        
        layout.addWidget(tabs)
        
        # 底部按钮
        button_layout = QHBoxLayout()
        save_button = QPushButton("保存")
        cancel_button = QPushButton("取消")
        
        save_button.clicked.connect(self.accept)
        cancel_button.clicked.connect(self.reject)
        
        button_layout.addWidget(cancel_button)
        button_layout.addWidget(save_button)
        
        layout.addLayout(button_layout)
    
    def get_api_key(self):
        return self.api_key_edit.text()
    
    def get_dark_mode(self):
        return self.dark_mode_checkbox.isChecked()

class ChatThread(QThread):
    """聊天处理线程"""
    response_ready = pyqtSignal(str)
    
    def __init__(self, api, messages):
        super().__init__()
        self.api = api
        self.messages = messages
    
    def run(self):
        response = self.api.generate_response(self.messages)
        self.response_ready.emit(response)

class ChatMessage(QWidget):
    """聊天消息组件"""
    def __init__(self, text, is_user=False, parent=None):
        super().__init__(parent)
        self.setMaximumWidth(400)
        
        layout = QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 创建消息气泡
        bubble = QFrame(self)
        bubble.setObjectName("userBubble" if is_user else "aiBubble")
        bubble.setStyleSheet("""
            #userBubble {
                background-color: #dcf8c6;
                border-radius: 10px;
                padding: 8px 12px;
                margin: 4px;
            }
            #aiBubble {
                background-color: white;
                border-radius: 10px;
                padding: 8px 12px;
                margin: 4px;
            }
        """)
        
        text_label = QLabel(text)
        text_label.setWordWrap(True)
        text_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        
        bubble_layout = QVBoxLayout(bubble)
        bubble_layout.addWidget(text_label)
        
        if is_user:
            layout.addStretch()
            layout.addWidget(bubble)
        else:
            layout.addWidget(bubble)
            layout.addStretch()

class WelcomePage(QWidget):
    """欢迎页面"""
    def __init__(self, main_window, parent=None):
        super().__init__(parent)
        self.main_window = main_window  # 直接保存对MainWindow的引用
        layout = QVBoxLayout(self)
        layout.setAlignment(Qt.AlignCenter)
        
        # DeepSeek图标
        icon_label = QLabel()
        self.icon_path = "deepseek_icon.png"  # 图标路径
        
        if os.path.exists(self.icon_path):
            icon_pixmap = QPixmap(self.icon_path)
            if not icon_pixmap.isNull():
                icon_label.setPixmap(icon_pixmap.scaled(120, 120, Qt.KeepAspectRatio, Qt.SmoothTransformation))
                icon_label.setAlignment(Qt.AlignCenter)
            else:
                icon_label.setText("DeepSeek")
                icon_label.setAlignment(Qt.AlignCenter)
                icon_label.setStyleSheet("font-size: 24px; font-weight: bold; color: #333;")
        else:
            icon_label.setText("DeepSeek")
            icon_label.setAlignment(Qt.AlignCenter)
            icon_label.setStyleSheet("font-size: 24px; font-weight: bold; color: #333;")
        
        # 欢迎文本
        welcome_label = QLabel("欢迎使用DeepSeek助手")
        welcome_label.setAlignment(Qt.AlignCenter)
        welcome_label.setStyleSheet("font-size: 18px; font-weight: bold; margin-top: 20px;")
        
        # 描述文本
        desc_label = QLabel("这是一个基于DeepSeek AI的桌面助手，可随时为您提供帮助。")
        desc_label.setAlignment(Qt.AlignCenter)
        desc_label.setStyleSheet("font-size: 14px; color: #666; margin-top: 10px;")
        
        # 开始按钮
        start_button = QPushButton("开始对话")
        start_button.setFixedSize(150, 40)
        start_button.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50;
                color: white;
                border-radius: 20px;
                font-size: 14px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
        """)
        start_button.clicked.connect(self.on_start_clicked)
        
        layout.addWidget(icon_label)
        layout.addWidget(welcome_label)
        layout.addWidget(desc_label)
        layout.addSpacing(30)
        layout.addWidget(start_button, 0, Qt.AlignCenter)
    
    def on_start_clicked(self):
        """开始按钮点击事件"""
        try:
            # 使用保存的MainWindow引用直接调用方法
            self.main_window.show_chat_page()
        except Exception as e:
            print(f"切换到聊天页面时出错: {e}")
            QMessageBox.critical(self, "错误", f"无法切换到聊天页面: {e}")

class ChatPage(QWidget):
    """聊天页面"""
    def __init__(self, api, parent=None):
        super().__init__(parent)
        self.api = api
        self.messages = []
        
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 聊天区域
        self.chat_scroll_area = QScrollArea()
        self.chat_scroll_area.setWidgetResizable(True)
        self.chat_scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        
        self.chat_widget = QWidget()
        self.chat_layout = QVBoxLayout(self.chat_widget)
        self.chat_layout.setAlignment(Qt.AlignTop)
        self.chat_layout.setSpacing(10)
        self.chat_layout.setContentsMargins(15, 15, 15, 15)
        
        self.chat_scroll_area.setWidget(self.chat_widget)
        
        # 分隔线
        separator = QFrame()
        separator.setFrameShape(QFrame.HLine)
        separator.setFrameShadow(QFrame.Sunken)
        
        # 输入区域
        input_layout = QHBoxLayout()
        
        self.message_input = QTextEdit()
        self.message_input.setPlaceholderText("输入消息...")
        self.message_input.setMaximumHeight(100)
        self.message_input.setAcceptRichText(False)
        
        self.send_button = QPushButton("发送")
        self.send_button.setFixedSize(80, 40)
        self.send_button.setStyleSheet("""
            QPushButton {
                background-color: #0084ff;
                color: white;
                border-radius: 5px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #0073e6;
            }
        """)
        self.send_button.clicked.connect(self.send_message)
        
        input_layout.addWidget(self.message_input)
        input_layout.addWidget(self.send_button)
        
        layout.addWidget(self.chat_scroll_area)
        layout.addWidget(separator)
        layout.addLayout(input_layout)
        
        # 初始提示
        self.add_message("你好！我是DeepSeek助手，有什么可以帮助你的吗？", False)
    
    def add_message(self, text, is_user=True):
        """添加消息到聊天区域"""
        message_widget = ChatMessage(text, is_user)
        self.chat_layout.addWidget(message_widget)
        
        # 滚动到底部
        QTimer.singleShot(100, self.scroll_to_bottom)
        
        # 如果是用户消息，添加到消息列表
        if is_user:
            self.messages.append({"role": "user", "content": text})
    
    def scroll_to_bottom(self):
        """滚动到聊天区域底部"""
        scroll_bar = self.chat_scroll_area.verticalScrollBar()
        scroll_bar.setValue(scroll_bar.maximum())
    
    def send_message(self):
        """发送消息"""
        text = self.message_input.toPlainText().strip()
        if not text:
            return
        
        # 添加用户消息
        self.add_message(text)
        self.message_input.clear()
        
        # 显示AI正在思考
        thinking_widget = ChatMessage("正在思考...", False)
        thinking_widget.setObjectName("thinkingBubble")
        thinking_widget.setStyleSheet("""
            #thinkingBubble {
                background-color: #f0f0f0;
                border-radius: 10px;
                padding: 8px 12px;
                margin: 4px;
            }
        """)
        thinking_id = self.chat_layout.count()
        self.chat_layout.addWidget(thinking_widget)
        self.scroll_to_bottom()
        
        # 在后台线程中获取AI回复
        self.thread = ChatThread(self.api, self.messages)
        self.thread.response_ready.connect(lambda response: self.on_response_ready(response, thinking_id))
        self.thread.start()
    
    def on_response_ready(self, response, thinking_id):
        """处理AI回复"""
        # 移除"正在思考"消息
        if thinking_id < self.chat_layout.count():
            thinking_widget = self.chat_layout.itemAt(thinking_id).widget()
            if thinking_widget:
                self.chat_layout.removeWidget(thinking_widget)
                thinking_widget.deleteLater()
        
        # 添加AI回复
        self.add_message(response, False)
        self.messages.append({"role": "assistant", "content": response})

class MainWindow(QMainWindow):
    """主窗口"""
    def __init__(self, api_key="", dark_mode=False):
        super().__init__()
        self.api = DeepSeekAPI(api_key)
        self.settings = {
            "api_key": api_key,
            "dark_mode": dark_mode
        }
        
        self.init_ui()
        self.load_settings()
        
        # 检查是否需要提示设置API
        if not self.settings["api_key"]:
            self.show_api_prompt()
    
    def init_ui(self):
        """初始化UI"""
        # 设置窗口标题和图标
        self.setWindowTitle("DeepSeek助手")
        
        # 检查图标文件是否存在
        icon_path = "deepseek_icon.png"
        if os.path.exists(icon_path):
            self.setWindowIcon(QIcon(icon_path))
        
        # 设置窗口大小和位置
        self.setGeometry(300, 300, 500, 600)
        
        # 中央部件
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.main_layout = QVBoxLayout(self.central_widget)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        
        # 欢迎页面 - 传递self（MainWindow实例）作为参数
        self.welcome_page = WelcomePage(self)
        self.main_layout.addWidget(self.welcome_page)
        
        # 聊天页面
        self.chat_page = ChatPage(self.api, self)
        
        # 创建系统托盘图标
        self.create_tray_icon()
        
        # 应用主题
        self.apply_theme()
    
    def create_tray_icon(self):
        """创建系统托盘图标"""
        self.tray_icon_menu = QMenu(self)
        
        self.show_action = QAction("显示", self)
        self.show_action.triggered.connect(self.showNormal)
        
        self.settings_action = QAction("设置", self)
        self.settings_action.triggered.connect(self.open_settings)
        
        self.quit_action = QAction("退出", self)
        self.quit_action.triggered.connect(self.quit_application)
        
        self.tray_icon_menu.addAction(self.show_action)
        self.tray_icon_menu.addAction(self.settings_action)
        self.tray_icon_menu.addSeparator()
        self.tray_icon_menu.addAction(self.quit_action)
        
        self.tray_icon = QSystemTrayIcon(self)
        
        # 检查图标文件是否存在
        icon_path = "deepseek_icon.png"
        if os.path.exists(icon_path):
            self.tray_icon.setIcon(QIcon(icon_path))
        else:
            # 使用默认图标（修复了QStyle的导入问题）
            self.tray_icon.setIcon(self.style().standardIcon(QStyle.SP_MessageBoxInformation))
        
        self.tray_icon.setContextMenu(self.tray_icon_menu)
        self.tray_icon.activated.connect(self.on_tray_icon_activated)
        self.tray_icon.show()
    
    def on_tray_icon_activated(self, reason):
        """托盘图标激活事件"""
        if reason == QSystemTrayIcon.Trigger:
            if self.isVisible():
                self.hide()
            else:
                self.showNormal()
                self.raise_()
    
    def show_chat_page(self):
        """显示聊天页面"""
        try:
            self.main_layout.removeWidget(self.welcome_page)
            self.welcome_page.hide()
            self.main_layout.addWidget(self.chat_page)
            self.chat_page.show()
            
            # 强制刷新布局
            self.central_widget.update()
            self.central_widget.repaint()
        except Exception as e:
            print(f"显示聊天页面时出错: {e}")
            QMessageBox.critical(self, "错误", f"无法显示聊天页面: {e}")
    
    def open_settings(self):
        """打开设置对话框"""
        dialog = SettingsDialog(
            self, 
            self.settings["api_key"], 
            self.settings["dark_mode"]
        )
        
        if dialog.exec_():
            # 保存设置
            self.settings["api_key"] = dialog.get_api_key()
            self.settings["dark_mode"] = dialog.get_dark_mode()
            self.api.set_api_key(self.settings["api_key"])
            self.save_settings()
            self.apply_theme()
            
            # 如果设置了新的API密钥，提示用户
            if dialog.get_api_key() and not dialog.get_api_key() == self.api.api_key:
                QMessageBox.information(
                    self, 
                    "API密钥设置", 
                    "API密钥已设置，现在可以开始对话了！"
                )
    
    def show_api_prompt(self):
        """显示API提示"""
        reply = QMessageBox.question(
            self, 
            "API密钥设置", 
            "您还没有设置DeepSeek API密钥，是否现在设置？",
            QMessageBox.Yes | QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            self.open_settings()
    
    def apply_theme(self):
        """应用主题"""
        if self.settings["dark_mode"]:
            # 深色主题
            self.setStyleSheet("""
                QMainWindow, QWidget {
                    background-color: #2d2d30;
                    color: #ffffff;
                }
                QLabel {
                    color: #ffffff;
                }
                QTextEdit, QLineEdit {
                    background-color: #3c3c3c;
                    color: #ffffff;
                    border: 1px solid #555555;
                    border-radius: 3px;
                }
                QPushButton {
                    background-color: #007acc;
                    color: #ffffff;
                    border: none;
                    padding: 5px 10px;
                    border-radius: 3px;
                }
                QPushButton:hover {
                    background-color: #0066aa;
                }
                QScrollArea {
                    background-color: #2d2d30;
                }
                QMenu {
                    background-color: #3c3c3c;
                    color: #ffffff;
                }
                QMenu::item:selected {
                    background-color: #007acc;
                }
            """)
        else:
            # 浅色主题
            self.setStyleSheet("""
                QMainWindow, QWidget {
                    background-color: #f5f5f5;
                    color: #333333;
                }
                QLabel {
                    color: #333333;
                }
                QTextEdit, QLineEdit {
                    background-color: #ffffff;
                    color: #333333;
                    border: 1px solid #cccccc;
                    border-radius: 3px;
                }
                QPushButton {
                    background-color: #0084ff;
                    color: #ffffff;
                    border: none;
                    padding: 5px 10px;
                    border-radius: 3px;
                }
                QPushButton:hover {
                    background-color: #0073e6;
                }
                QScrollArea {
                    background-color: #f5f5f5;
                }
                QMenu {
                    background-color: #ffffff;
                    color: #333333;
                }
                QMenu::item:selected {
                    background-color: #0084ff;
                    color: #ffffff;
                }
            """)
    
    def load_settings(self):
        """加载设置"""
        try:
            settings = QSettings("DeepSeekAssistant", "Settings")
            self.settings["api_key"] = settings.value("api_key", "")
            self.settings["dark_mode"] = settings.value("dark_mode", False, type=bool)
            self.api.set_api_key(self.settings["api_key"])
        except Exception as e:
            print(f"加载设置失败: {str(e)}")
            QMessageBox.warning(self, "设置加载失败", f"无法加载保存的设置: {str(e)}")
    
    def save_settings(self):
        """保存设置"""
        try:
            settings = QSettings("DeepSeekAssistant", "Settings")
            settings.setValue("api_key", self.settings["api_key"])
            settings.setValue("dark_mode", self.settings["dark_mode"])
        except Exception as e:
            print(f"保存设置失败: {str(e)}")
            QMessageBox.warning(self, "设置保存失败", f"无法保存设置: {str(e)}")
    
    def closeEvent(self, event):
        """关闭事件"""
        if self.tray_icon.isVisible():
            QMessageBox.information(
                self, 
                "DeepSeek助手", 
                "程序将继续在系统托盘中运行。要完全退出程序，请在系统托盘图标上右键点击并选择'退出'。"
            )
            self.hide()
            event.ignore()
        else:
            event.accept()
    
    def quit_application(self):
        """完全退出应用程序"""
        self.tray_icon.hide()
        QApplication.quit()

if __name__ == "__main__":
    try:
        # 确保可以正确处理高DPI显示器
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
        QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
        
        app = QApplication(sys.argv)
        
        # 设置应用程序样式
        app.setStyle("Fusion")
        
        # 确保中文显示正常
        font_families = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC", "Microsoft YaHei"]
        font_set = False
        
        for font_family in font_families:
            font = QFont(font_family)
            if font.exactMatch():
                app.setFont(font)
                font_set = True
                print(f"成功设置字体: {font_family}")
                break
        
        if not font_set:
            # 使用系统默认字体
            font = QFont()
            app.setFont(font)
            print("使用系统默认字体")
        
        # 显示主窗口
        window = MainWindow()
        window.show()
        
        sys.exit(app.exec_())
    except Exception as e:
        # 显示详细错误信息
        error_msg = f"程序启动失败！\n\n错误类型: {type(e).__name__}\n错误信息: {str(e)}"
        QMessageBox.critical(None, "启动错误", error_msg)
        print(f"错误详情: {str(e)}")
        # 移除了input("按Enter键退出...")，避免windowed模式下访问stdin
